<template>
  <div class="manageProduct">
    <div class="btnGrounp">
      <el-button @click="handleEdit(0)">新增产品</el-button>
    </div>
    <div class="search">
      <ul>
        <li>
          <span>所属一级分类</span>
          <el-select v-model="search.classLevel1" placeholder="请选择" @visible-change='getAllClassOne'>
            <el-option v-for="item in search.classLevel1Options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </li>
        <li>
          <span>所属二级分类</span>
          <el-select v-model="search.classLevel2" placeholder="请选择" @visible-change='getAllClassTwo'>
            <el-option v-for="item in search.classLevel2Options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </li>
        <li>
          <span>产品名称</span>
          <el-input v-model="search.productName" placeholder="请输入内容" @keyup.enter.native="searchProduct"></el-input>
        </li>
        <li class="lastLi">
          <el-button @click="searchProduct">查询</el-button>
        </li>
      </ul>
    </div>
    <div class="content">
       <el-table :data="contentData" style="width: 100%" stripe :header-cell-class-name='lastTaHead'>
        <el-table-column prop="sort" label="序号" width="20%"  align='center'></el-table-column>
        <el-table-column prop="chinaName" label="产品名称" width="30%"  align='center'></el-table-column>
        <el-table-column label="展示图" width="20%" align='center'>
          <template slot-scope="scope">
            <img :src="scope.row.coverIcon" alt="">
          </template>
        </el-table-column>
        <el-table-column label="详情图" width="20%" align='center'>
          <template slot-scope="scope">
            <img :src="scope.row.detailIcon" alt="">
          </template>
        </el-table-column>
        <el-table-column prop="oneClassName" label="所属一级分类" width="30%" align='center' ></el-table-column>
        <el-table-column prop="twoClassName" label="所属二级分类" width="30%" align='center' ></el-table-column>
        <el-table-column prop="gmtCreated" label="发布时间" width="40%" align='center' show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" align='center' width="100%" class-name='lastTd'>
          <template slot-scope="scope">
            <el-button class="edit" size='mini'  @click="handleEdit(1,scope.$index, scope.row)">编辑</el-button>
            <el-button  class="delete" size='mini' type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            <el-button class="adjust"  size='mini' @click="handleAdjust(scope.$index, scope.row)" v-if='scope.row.showAdjust'>调整排序</el-button>
            <div class="adjustSort" v-else>
              <el-input v-model="scope.row.adjustValue" placeholder="请输入内容" @keyup.enter.native="sureAdjust(scope.row.id,scope.row)"></el-input> <el-button class="defaultBtn" @click="sureAdjust(scope.row.id,scope.row)">确定</el-button>
            </div>
          </template>
        </el-table-column >
      </el-table>
    </div>
    <!-- 弹框 -->
    <!-- <div class="dialog">
      <el-dialog :title="formTitle" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item label="图标" label-width="7.5rem">
            <el-upload class="avatar-uploader" action="111"   :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          </el-form-item>
           <el-form-item label="分类名" label-width="7.5rem">
          </el-form-item>
          <el-form-item label="中文" label-width="7.5rem">
            <el-input v-model="form.chinese" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="英文" label-width="7.5rem">
            <el-input v-model="form.english" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
        </div>
      </el-dialog>
    </div> -->
    <div class="paging">
      <el-pagination :page-size="pageSize"  layout="prev, pager, next" :total="totalNum" @current-change='changeCurrentPage'></el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  name: 'manageProduct',
  data () {
    return {
      search:{
        classLevel1:'',
        classLevel1Options: [],
        classLevel2:'',
        classLevel2Options: [
          {
            value: '选项1',
            label: '黄金糕'
          }, {
            value: '选项2',
            label: '双皮奶'
          }, {
            value: '选项3',
            label: '蚵仔煎'
          }, {
            value: '选项4',
            label: '龙须面'
          }, {
            value: '选项5',
            label: '北京烤鸭'
          }
        ],
        productName:'',//产品名称
      },//查询对象
      //内容数据
      contentData: [],
      pageSize:7,//每页显示条目个数
      totalNum:7,//总条目数   
      currentPage:1,
      // formTitle: '编辑',//表单标题
      // dialogFormVisible:false,//对话框是否可见
      // //对话框表单
      // form: {
      //     imageUrl: '',
      //     chinese: '',
      //     english: '',
      //   },
      // // upLoadData:{//上传时附带的其他参数
      // //     srid:''
      // // }
    }
  },
  methods: {
    //新增/编辑行
    handleEdit(type,index, row) {
      let _this = this;
      //console.log(type,index, row);
      // _this.dialogFormVisible = true;//显示对话框

      if(type == 0){//新增操作
        // _this.formTitle = '新增';
        _this.$router.push({
          path:'/operateProduct/add/-1'
        });
      }else{//编辑操作
        // _this.formTitle = '编辑';
        _this.$router.push({
          path:'/operateProduct/edit/'+row.id
        });
      }

    },
    //删除行
    handleDelete(index, row) {
      let _this = this;
      //console.log(index, row);
      _this.$confirm('是否删除?',  {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let sessionId = _this.$store.state.id;//获取token 
          let api = '/api/product/delete?id='+row.id;
           _this.axios({
            url:api,
            method: 'post',
            headers:{
              sessionId,
            }		
  			}).then(res=>{
            //console.log('删除行',res)
            if(res.data.code == 401){
                _this.$message({
                  type: 'info',
                  message: '登录已失效，请重新登录'
                });  
                _this.$router.push({
                  path:"/"
                });
                return
            }
            if(res.data.code == 200){
              _this.$message({
                type: 'success',
                message: '删除成功!'
              });
              _this.getAllProduct();//刷新
            }
          });
        }).catch(() => {
          _this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    //调整排序
    //调整排序
    handleAdjust(index, row) {
      let _this = this;
      //注意showAdjust是数组每一个对象元素添加属性，层次[{}]太深,且不是vue实例化时指定，所以出现了数据更改，
      //页面没有热响应的情况，需要用$set方法修改媒体{}的showAdjust属性，且用数组的splice热响应监听方法对
      //数组进行修改
      // _this.$set(row, 'showAdjust', false)
      // _this.contentData.splice(index, 1, row);
      // debugger
      _this.contentData.forEach((item,indexs)=>{
        //console.log(indexs, item);
        if(indexs == index){
          _this.$set(item, 'showAdjust', false)
          
        }else{
           _this.$set(item, 'showAdjust', true)
        }
        _this.contentData.splice(indexs, 1, item);

      });
      // _this.$forceUpdate();//强制刷新
      //console.log(index, row,_this.contentData);


    },
    //确定调整
    sureAdjust(id,row){
      let _this = this;
      let api = '/api/product/changeSort?id='+id+'&sort='+row.adjustValue;
      let sessionId = _this.$store.state.id;//获取token
      _this.axios({
            url:api,
            method: 'post',
            headers:{
              sessionId,
            }		
  			}).then(res=>{
        //console.log('确认修改顺序',res);
        if(res.data.code == 401){
            _this.$message({
              type: 'info',
              message: '登录已失效，请重新登录'
            });  
            _this.$router.push({
              path:"/"
            });
            return
          }
          if(res.data.code == 200){
            _this.$message({
              type: 'success',
              message: '修改成功！'
            }); 
            _this.getAllProduct();//刷新
          }
      });
    },
    //改变当前页
    changeCurrentPage(val){
      //console.log(`当前页: ${val}`);
      let _this = this;
      _this.currentPage = val;
      _this.getAllProduct();//调用同一接口
    },
    //最后一列的表头
    lastTaHead({row, column, rowIndex, columnIndex}){
      let _this = this;
      if(columnIndex == 7){
        return 'lastTd lastTdHead'
      }
    },
    //获取所有产品
    getAllProduct(searchPage){
      let _this = this;
      let api = '/api/product/find_page';
      let sessionId = _this.$store.state.id;//获取token
      _this.axios.post(api,{
          "classTwoId": _this.search.classLevel2,
          "pageIndex": searchPage == 1?searchPage:_this.currentPage,
          "pageSize": 7,
          "chinaNameLike": _this.search.productName,
          "classOneId": _this.search.classLevel1,
      },{
        headers:{
          sessionId,
        }
      }).then(res=>{
        //console.log('所有产品',res)
        if(res.data.code == 401){
            _this.$message({
              type: 'info',
              message: '登录已失效，请重新登录'
            });  
            _this.$router.push({
              path:"/"
            });
            return
          }
          if(res.data.code == 403){
            _this.$message({
              type: 'info',
              message: res.data.status
            });  
            return
          }
        if(res.data.code == 200){
          _this.totalNum = res.data.data.count;//获取总条数
          _this.contentData = res.data.data.bussData;
          _this.contentData.forEach(item=>{
            item.showAdjust = true;
            item.gmtCreated = new Date(item.gmtCreated).format("yyyy-MM-dd hh:mm:ss");
          });
        }
      });
    },
    //查询产品
    searchProduct(){
      let _this = this;
      _this.getAllProduct(1);//调用同一接口
    },
   // //获取所有一级分类
    getAllClassOne(isShow){
      let _this = this;
      //console.log(isShow,'下拉框是否出现');
      if(!isShow){
        return
      }
      let api = '/api/sysClassOne/find_list';
      let sessionId = _this.$store.state.id;//获取token
      let optionsOne = [];//清空   
      _this.axios({
            url:api,
            method: 'post',
            headers:{
              sessionId,
            }		
  			}).then(res=>{
        //console.log('查询所有的一级分类',res)
             
        let class1 = res.data.data.bussData;
        class1.forEach(item=>{
          let obj = {};
          obj.value = item.id;
          obj.label = item.chinaName;
          optionsOne.push(obj);
          // _this.form.class1Options.push(obj);
        });
        // //console.log('optionsOne',optionsOne);
        optionsOne = optionsOne.filter(item=>{
          return item.label != '全部'
        });
        _this.$store.dispatch('saveClassOne',optionsOne);//缓存所有一级分类
        // _this.search.classLevel1Options =[];
        _this.search.classLevel1Options = _this.$store.state.classOneOptions;//获取所有第一分类
        let obj = {
          value:"",
          label:"全部",
        }

        _this.search.classLevel1Options.unshift(obj);
        _this.search.classLevel2 = '';
        //console.log('saveClassOne',optionsOne,_this.$store.state.classOneOptions);


      });
    },
    //获取所有二级分类
    getAllClassTwo(isShow){
      let _this = this;
      //console.log(isShow,'下拉框是否出现');
      if(!isShow){
        return
      }
      let api = '/api/sysClassTwo/find_list';
      let optionsTwo = [];//清空
      let sessionId = _this.$store.state.id;//获取token
      _this.axios({
            url:api,
            method: 'post',
            headers:{
              sessionId,
            }		
  			}).then(res=>{
        //console.log('所有的二级分类',res);
        let class2 = res.data.data.bussData;
        
        class2 = class2.filter(item=>{
          return item.label != '全部'
        });
        _this.$store.dispatch('saveClassTwo',class2);//缓存所有二级分类
        
        //console.log('classTwoOptions',optionsTwo,_this.$store.state.classTwoOptions);
        // _this.search.classLevel2Options =[];
        _this.search.classLevel2Options = _this.$store.state.classTwoOptions;//获取所有二级分类
        _this.search.classLevel2Options.forEach(item=>{
          // let obj = {};
          item.value = item.id;
          item.label = item.chinaName;
          // optionsTwo.push(obj);
        });
        let obj = {
          value:"",
          label:"全部",
        }

        _this.search.classLevel2Options.unshift(obj);
        if(_this.search.classLevel1 != ''){
          _this.search.classLevel2Options = _this.search.classLevel2Options.filter(item=>{
            //console.log(_this.search.classLevel1);
            return item.classOneId == _this.search.classLevel1
          });
        }
        
        //console.log('过滤classTwoOptions',_this.search.classLevel2Options,_this.$store.state.classTwoOptions);



      });
    },
  },
  mounted(){
    let _this = this;
    _this.getAllProduct();//获取所有产品
    _this.getAllClassOne(true);//获取所有一级分类
    _this.getAllClassTwo(true);//获取所有二级分类
    // if(_this.$store.state.classOneOptions.length == 0){
    //   _this.getAllClassOne();//获取所有一级分类

    // }else{
    //   _this.search.classLevel1Options = _this.$store.state.classOneOptions;//获取所有第一分类
    // }
    // _this.getAllClassTwo();//获取所有二级分类
    // _this.search.classLevel1Options =[];
    // _this.search.classLevel2Options =[];
    // _this.search.classLevel1Options = _this.$store.state.classOneOptions;//获取所有第一分类
    // _this.search.classLevel2Options = _this.$store.state.classTwoOptions;//获取所有二级分类
    // let obj = {
    //   value:"",
    //   label:"全部",
    // }

    // _this.search.classLevel1Options.unshift(obj);
    // _this.search.classLevel1 = '';
    // _this.search.classLevel2Options.unshift(obj);
    // _this.search.classLevel2 = '';

    // //console.log(_this.search.classLevel1Options,'_this.search.classLevel1Options',_this.search.classLevel2Options,'_this.search.classLevel2Options');




    Date.prototype.format = function(fmt) { 
        var o = { 
            "M+" : this.getMonth()+1,                 //月份 
            "d+" : this.getDate(),                    //日 
            "h+" : this.getHours(),                   //小时 
            "m+" : this.getMinutes(),                 //分 
            "s+" : this.getSeconds(),                 //秒 
            "q+" : Math.floor((this.getMonth()+3)/3), //季度 
            "S"  : this.getMilliseconds()             //毫秒 
        }; 
        if(/(y+)/.test(fmt)) {
                fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
        }
        for(var k in o) {
            if(new RegExp("("+ k +")").test(fmt)){
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
            }
        }
        return fmt; 
    } 
  }
}
</script>

<style scoped>
/* 整体样式 */
.manageProduct{
  height: 100%;
  width: 100%;
  position: relative;
  padding-left: 2%;
}
.manageProduct>>>.btnGrounp .el-button{
  background-color: rgba(53, 174, 160, 1);
  color: rgb(255, 255, 255,1);
}
/* 查询 */
.manageProduct>>>.search{
  width: 100%;
  height: 10%;
  line-height: 10%;
  position: absolute;
  top: 10%;
  font-size: .875rem;
}
/* 输入框 */
.manageProduct>>>.el-input{
  width: 70%;
}
/* 输入框 */
.manageProduct>>>.el-select{
  width: 50%;
}
/* 选择框下的输入框 */
.manageProduct>>>.el-select .el-input{
  width: 100%;
}
.manageProduct>>>.search ul{
  width: 100%;
  height: 100%;
  display: flex;
  
}
.manageProduct>>>.search ul li{
  /* flex:1; */
  padding-right: 1%;
}
.manageProduct>>>.search ul li.lastLi{
    position:absolute;
    right: 15%;
}
.manageProduct>>>.search ul li span{
  padding-right: 2%;
}
.manageProduct>>>.search ul li.lastLi button{
  color:rgba(16, 16, 16, 1);
}
/* 主要内容 */
.manageProduct>>>.content{
  width: 85%;
  position: absolute;
  top: 21%;
  color: rgba(16, 16, 16, 1) !important;
}
.manageProduct>>>.content img{
  width: 21%;
}
.manageProduct>>>.content table{
  width: 100% !important;
}
.manageProduct>>>.content table td>div{
  width: 100% !important;
}
/* table无数据时的显示 */
.manageProduct>>>.el-table__empty-block{
   width: 100% !important;
}
/* 最后一列 */
.manageProduct>>>.lastTd{
  text-align: left;
  padding-left: 2%;
}
/* 消除表头变形 */
.manageProduct>>>table .gutter{
  display: block !important;
}
.manageProduct>>>.lastTd .cell{
   height: 1.75rem;
  line-height: 1.75rem;

}
/* .manageProduct>>>.lastTd .cell{
  height: 20%;
  line-height: 20%;
} */
/* 最后一列表头 */
.manageProduct>>>.lastTdHead{
  padding-left: 10%;
}
/* 表格内的按钮 */
.manageProduct>>>.content table .defaultBtn{
  color: rgba(16, 16, 16, 1);
}
/* 编辑按钮 */
.manageProduct>>>.edit{
  background-color: rgba(63, 81, 181, 1);
}
/* 删除按钮 */
.manageProduct>>>.delete{
  background-color: rgba(229, 28, 35, 1);
}
/* 调整排序按钮 */
.manageProduct>>>.adjust{
  background-color: rgba(139, 195, 74, 1);

}
/* 调整排序输入框 */
.manageProduct>>>.adjustSort{
  display: inline-block;
  height: 92%;
  width: 60%;
}
.manageProduct>>>.adjustSort .el-input{
  width: 42%;
  height: 100%;

}
.manageProduct>>>.adjustSort .el-input input{
  height: 100%;
}
.manageProduct>>>.adjustSort .el-input__inner{
  /* height: 1.9375rem; */
}
.manageProduct>>>.adjustSort .el-button{
  line-height: 0.07;
  /* height: 100%;
  line-height: 1.75rem; */

}
/* 分页 */
.manageProduct>>>.paging{
  position: absolute;
  bottom: -8%;
  text-align: center;
  width: 85%;
}
/* 对话框 */
/* .manageProduct>>>.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .manageProduct>>>.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .manageProduct>>>.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .manageProduct>>>.avatar {
    width: 178px;
    height: 178px;
    display: block;
  } */
</style>
